﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace console.demo.thread
{
    public class Print
    {
        public Print() { }

        /// <summary>
        ///  两个线程交替打印0-100的奇偶数
        /// </summary>
        public static void PrintOddEventNumber() {
            var work = new ThreadWorkTest();
            var thread1 = new Thread(work.PrintOddNumber) { Name = "奇数" };
            var thread2 = new Thread(work.PrintEvenNumber) { Name = "偶数" };
            thread1.Start();
            thread2.Start();
        }

      
    }

    public class ThreadWorkTest { 
            private static readonly AutoResetEvent oddAre=new AutoResetEvent(false);
           private  static readonly AutoResetEvent evenAre=new AutoResetEvent(false);

        /// <summary>
        /// 打印奇数
        /// </summary>
        public void PrintOddNumber() { 
              oddAre.WaitOne();
            for (int i = 0; i <=100; i++) {
                if (i % 2 != 1) continue;
                Console.WriteLine($"{Thread.CurrentThread.Name}:{i}");
                evenAre.Set();
                oddAre.WaitOne();
            }
        }

        /// <summary>
        /// 打印偶数
        /// </summary>
        public  void PrintEvenNumber()
        {
            for (int i = 0; i <=100; i++)
            {
                if (i % 2 != 0) continue;
                Console.WriteLine($"{Thread.CurrentThread.Name}:{i}");
                oddAre.Set();
                evenAre.WaitOne();
            }
        } 
    }
}
